import React from 'react';
import { Form, Input, Button, Row, Col, Flex, App } from 'antd';
import { useNavigate } from 'react-router';
import { LeftOutlined } from '@ant-design/icons';

import CountdownButton  from './CountdownButton.js';
import { send, verify } from '../../apis/email.js';

const Email = ({setCurrentStep, setEmail}) => {
  const navigate = useNavigate(); // 用于 React Router 跳转
  const [form] = Form.useForm();
  const { message } = App.useApp();

  // 提交表单
  const verifyEmail = async ({email, code}) => {
    const res = await verify({email, code});
    if(res.success){
      message.success('校验通过');
      setCurrentStep(1);
      setEmail(email);
    }
  };

  // 处理获取验证码按钮
  const handleGetCode = async (startCountdown) => {
    let email;
    try {
      ({ email } = await form.validateFields(['email']));
    } catch (e) {
      console.error('请输入邮箱');
      return;
    }
    const res = await send({ email });
    if (res.success) {
      message.success('已发送，请于10分钟内完成注册');
      startCountdown();
    }
  };

  return (
    <Flex vertical style={{ width: '400px', margin: '20px auto' }}>
      {/* 返回按钮 */}
      {/*<Button type='link' icon={<LeftOutlined />} style={{ marginBottom: '20px' }}>*/}
      <Button
        type='default'
        onClick={() => navigate('/login')}
        style={{ marginBottom: '24px', width: 'fit-content' }}>
        <LeftOutlined/>返回登录页
      </Button>

      {/* 表单内容 */}
      <Form form={form} layout="vertical" onFinish={verifyEmail}>
        {/* 邮箱输入框 + 获取验证码按钮 */}
        <Form.Item
          name='email'
          validateTrigger='onBlur'
          rules={[
            { required: true, message: '请输入注册邮箱' },
            { type: 'email', message: '请输入正确的邮箱格式' }
          ]}
        >
          <Row gutter={8}>
            <Col span={16}>
              <Input placeholder='输入注册邮箱'/>
            </Col>
            <Col span={8}>
              <CountdownButton onClick={handleGetCode}></CountdownButton>
            </Col>
          </Row>
        </Form.Item>

        {/* 验证码输入框 */}
        <Form.Item
          name='code'
          validateTrigger='onBlur'
          rules={[{ required: true, message: '请输入验证码' }]}
        >
          <Input placeholder='输入验证码'/>
        </Form.Item>

        {/* 验证按钮 */}
        <Form.Item>
          <Button
            type='primary'
            htmlType='submit'
            style={{ width: '100%' }}
          >
            验证
          </Button>
        </Form.Item>
      </Form>
    </Flex>
  );
};

export default Email;
